package com.haiyou.common.spring.filter;

import java.io.IOException;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.haiyou.common.system.Properties;
import com.haiyou.common.util.ip.IpUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * 
 * @Description: actuator 端口过滤器
 * @author xingyuan
 * @date 2022年8月22日 下午3:59:10
 */
@Slf4j
public class ActuatorFilter implements Filter{

	@Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest)servletRequest;

        String ip = IpUtil.getIpAddr(request);
        
        List<String> ips = Properties.actuator_ip_white();
        
        boolean white  = ips.stream().anyMatch(item -> ip.startsWith(item));
        
        if(!white) {
    		String url = request.getRequestURI().substring(request.getContextPath().length());
    		log.info("异常请求 url:{},ip:{}",url,ip);
        	throw new RuntimeException ("ip not allow");
        }
        
        filterChain.doFilter(servletRequest,servletResponse);
	}

}
